package com.woniuxy.aspect;


import com.woniuxy.entity.po.system.Log;
import com.woniuxy.entity.po.system.User;
import com.woniuxy.service.LogService;
import com.woniuxy.util.DesensitizationUtils;
import com.woniuxy.util.IpUtils;
import com.woniuxy.util.JWTUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @BelongsProject: community
 * @BelongsPackage: com.woniuxy.aspect
 * @Author: Quan
 * @Date: 2025/3/3 15:07
 */
@Component
@Aspect
@EnableAspectJAutoProxy
public class LogAspect {
	private final String POINTCUT = "execution(* com.woniuxy.controller.*.*(..))";
	@Resource
	LogService logService;

	@Around(POINTCUT)
	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
		System.out.println("=============================");

		// 获取当前请求的上下文
		ServletRequestAttributes servletRequestAttributes =
				(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = servletRequestAttributes.getRequest();

		String token = request.getHeader("token");
		String username = null;
		if (token != null) {
			username = JWTUtil.getUsername(token);
		}

		Log log = new Log();
		// 获取用户名
		log.setUsername(username == null ? "未登录" : DesensitizationUtils.desensitizeName(username));
		// 获取ip地址
		log.setIp(IpUtils.getClientIp(request));
		// 获取uri地址
		log.setRequestUrl(request.getRequestURI());
		// 获取请求方法
		log.setRequestMethod(request.getMethod());
		// 获取类名
		log.setClassName(joinPoint.getSignature().getDeclaringTypeName());
		// 获取方法名
		log.setMethodName(joinPoint.getSignature().getName());
		// 计算时间戳以及开始结束时间
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		long beforeProceed = System.currentTimeMillis();
		LocalDateTime startTime = LocalDateTime.now();
		log.setStartTime(startTime.format(timeFormatter));
		// 运行被代理方法
		Object proceed = joinPoint.proceed();

		LocalDateTime endTime = LocalDateTime.now();
		log.setEndTime(endTime.format(timeFormatter));
		long afterProceed = System.currentTimeMillis();
		log.setRunTime(afterProceed - beforeProceed);
		// 将log添加到数据库中
		logService.addLog(log);
		System.out.println("=============================");
		return proceed;
	}
}
